#!/usr/bin/env node
// stats.js — counts source lines (excluding node_modules) and node_modules size
const fs = require('fs');
const path = require('path');

async function walk(dir, fileCallback) {
  const entries = await fs.promises.readdir(dir, { withFileTypes: true });
  for (const e of entries) {
    const full = path.join(dir, e.name);
    if (e.isDirectory()) {
      await walk(full, fileCallback);
    } else if (e.isFile()) {
      await fileCallback(full);
    }
  }
}

async function countLines(root) {
  let files = 0;
  let lines = 0;
  const extKeep = new Set(['.js', '.mjs', '.cjs', '.json', '.md']);
  await walk(root, async (file) => {
    // ignore node_modules
    if (file.split(path.sep).includes('node_modules')) return;
    const ext = path.extname(file).toLowerCase();
    if (!extKeep.has(ext)) return;
    files++;
    const content = await fs.promises.readFile(file, 'utf8');
    lines += content.split('\n').length;
  });
  return { files, lines };
}

async function folderSize(dir) {
  let total = 0;
  try {
    await walk(dir, async (file) => {
      try {
        const st = await fs.promises.stat(file);
        total += st.size;
      } catch (e) {}
    });
  } catch (e) {
    return 0;
  }
  return total;
}

function human(n) {
  if (n === 0) return '0 B';
  const units = ['B','KB','MB','GB'];
  let i = 0;
  let v = n;
  while (v >= 1024 && i < units.length-1) { v /= 1024; i++; }
  return `${v.toFixed(2)} ${units[i]}`;
}

(async ()=>{
  const root = path.resolve(__dirname, '..');
  console.log('Project root:', root);
  const { files, lines } = await countLines(root);
  console.log(`Source files counted: ${files}`);
  console.log(`Source lines (approx): ${lines}`);

  const nm = path.join(root, 'node_modules');
  const nmSize = await folderSize(nm);
  console.log(`node_modules size: ${human(nmSize)} (${nmSize} bytes)`);

  // package.json size
  try {
    const pj = await fs.promises.readFile(path.join(root, 'package.json'),'utf8');
    const pjSize = Buffer.byteLength(pj,'utf8');
    console.log(`package.json size: ${pjSize} bytes`);
  } catch (e) {}

  process.exit(0);
})();
